package com.marketingexpert.controller.marketingmgnt;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.config.Configuration;
import com.marketingexpert.dao.AuthorityDao;
import com.marketingexpert.domain.User;
import com.marketingexpert.domain.permission.ResourceUseRecord;
import com.marketingexpert.domain.permission.Role;
import com.marketingexpert.domain.permission.UserRole;
import com.marketingexpert.service.usermgnt.UserService;
import com.marketingexpert.util.Resources;

public class LoadAuthorityInfo implements Controller {

	private AuthorityDao authorityDao;
	
	private Configuration configuration;
	
	private UserService userService;
	
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		response.setContentType("application/x-json;charset=GBK"); 
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Cache-Control", "no-store"); 
		response.setDateHeader("Expires", 0);  
		PrintWriter out = response.getWriter(); 
		
		String recType = request.getParameter("recType");

		String parentUserId = (String) request.getSession().getAttribute("parentUserId");
		User parentUser = getUserService().queryUserByUId(parentUserId);
		UserRole ur = authorityDao.getUserRole(parentUserId);
		Role role = authorityDao.getRole(ur.getRoleId());
		
		role.setRoleName(Resources.getString(role.getRoleIdentify()));
		
		ResourceUseRecord rur = authorityDao.queryAlreadyUserByPId(parentUser.getId(), recType);
		
		int alreadyUseCounts = 0;
		
		if(rur != null) {
			alreadyUseCounts = rur.getUserCounts();
		}
		
		int totaoCanUse = configuration.getCanUseCounts(recType, role.getRoleIdentify());
		role.setTotalCanUseCounts(totaoCanUse);
		
		role.setRemainCounts(totaoCanUse - alreadyUseCounts);		
		
		JSONObject roleJson = JSONObject.fromObject(role);
		out.print(roleJson);
		return null;
	}

	public AuthorityDao getAuthorityDao() {
		return authorityDao;
	}

	public void setAuthorityDao(AuthorityDao authorityDao) {
		this.authorityDao = authorityDao;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
